package com.ykdl.member.kid.circle;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.ref.SoftReference;
import java.net.URLEncoder;
import java.util.ArrayList;

import net.bither.util.NativeUtil;
import net.wxxr.dataparse.model.DataParseError;
import net.wxxr.dataparse.model.DataState;
import net.wxxr.http.interfaces.ITag;
import net.wxxr.http.request.HttpBaseRequest;
import oauth.signpost.http.HttpParameters;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.umeng.analytics.MobclickAgent;
import com.ykdl.member.base.QLog;
import com.ykdl.member.constant.KidConfig;
import com.ykdl.member.kid.R;
import com.ykdl.member.kid.beans.GetUser_ScoreBean;
import com.ykdl.member.kid.beans.ImageBean;
import com.ykdl.member.kid.beans.TopicAndPostResultBean;
import com.ykdl.member.kid.gears.BaseScreen;
import com.ykdl.member.kid.models.FileMetas;
import com.ykdl.member.kid.util.CameraHelp;
import com.ykdl.member.kid.widget.dialog.DialogCallBack;
import com.ykdl.member.kid.widget.dialog.DialogImpl;
import com.ykdl.member.kid.widget.dialog.IDialog;
import com.ykdl.member.views.SelectToolDataView;
import com.ykdl.net.manager.TaskManager;
import com.ykdl.net.manager.Wxxr;

public class NewTopicActivity extends BaseScreen implements OnClickListener{
	private String groupsid ="20";
	private EditText send_topic_text ;
	private SelectToolDataView selToolData ;
	private ImageView photo1 ,photo2,photo3,photo4 ;
	private LinearLayout seltool_imgs ;
	private RelativeLayout seltool_imgs_div_1,seltool_imgs_div_2,seltool_imgs_div_3,seltool_imgs_div_4;
	private ArrayList<SoftReference<Bitmap>> mBitmapRefs = new ArrayList<SoftReference<Bitmap>>();  
	private ArrayList<ImageBean> photopath = new ArrayList<ImageBean>();
	private ArrayList<ImageBean> nt_photopath = new ArrayList<ImageBean>();
	private DialogImpl  dialog = new DialogImpl();
	private DisplayImageOptions options;
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTopTitle("发布新帖", 0, R.drawable.back_bg, new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (send_topic_text.getText().toString().length()>0||photopath.size()>0) {
					inintdialog();
				}else {
					finish();
				}
			}
		}, R.string.send_sina, 0, new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (photopath.size()>0) {
					File file = new File(photopath.get(0).getPath());
					putphoto(file);
				}else {
					getTopiclist();
				}
			}
		}, R.drawable.title_bg, false);
		options = new DisplayImageOptions.Builder()
		.showImageOnLoading(R.drawable.load_lost_bg)            //加载图片时的图片  
        .showImageForEmptyUri(R.drawable.load_lost_bg)         //没有图片资源时的默认图片  
        .showImageOnFail(R.drawable.load_lost_bg) 
		.showStubImage(R.drawable.load_lost_bg)
		.resetViewBeforeLoading(true)
		.cacheOnDisc(true)
		.cacheInMemory(true)
		.imageScaleType(ImageScaleType.EXACTLY)
		.bitmapConfig(Bitmap.Config.RGB_565)
		.considerExifParams(true)
		.displayer(new FadeInBitmapDisplayer(300))
		.build();
		groupsid = this.getIntent().getStringExtra("group_id");
		setContent(R.layout.newtopicactivity_xml);
		send_topic_text = (EditText)findViewById(R.id.send_topic_text);
		selToolData = (SelectToolDataView)findViewById(R.id.share_data_panle);
		seltool_imgs = (LinearLayout)findViewById(R.id.seltool_imgs);
		selToolData.setOwerActivity(this);
		selToolData.setEditText(send_topic_text,seltool_imgs);
		photo1 = (ImageView)findViewById(R.id.photo1);
		photo2 = (ImageView)findViewById(R.id.photo2);
		photo3 = (ImageView)findViewById(R.id.photo3);
		photo4 = (ImageView)findViewById(R.id.photo4);
		findViewById(R.id.close1).setOnClickListener(this);
		findViewById(R.id.close2).setOnClickListener(this);
		findViewById(R.id.close3).setOnClickListener(this);
		findViewById(R.id.close4).setOnClickListener(this);
		seltool_imgs_div_1 = (RelativeLayout)findViewById(R.id.seltool_imgs_div_1);
		seltool_imgs_div_2 = (RelativeLayout)findViewById(R.id.seltool_imgs_div_2);
		seltool_imgs_div_3 = (RelativeLayout)findViewById(R.id.seltool_imgs_div_3);
		seltool_imgs_div_4 = (RelativeLayout)findViewById(R.id.seltool_imgs_div_4);
		}
	private void getTopiclist() {
		String message = send_topic_text.getText().toString() ;
		if (send_topic_text.getText().toString().trim().length()>0) {
			showProgress("正在发送请稍等...");
			String  pageurl = KidConfig.GET_ALL_GROUPS+"/"+groupsid+"/"+"topics";
			HttpParameters bodyParams = new HttpParameters();
			
			try {
				message = URLEncoder.encode(message, "utf8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (nt_photopath.size()>0) {
				StringBuffer sb = new StringBuffer();
				if (nt_photopath.size()>1) {
					sb.append(nt_photopath.get(0).getFile_id());
					for (int i = 1; i < nt_photopath.size(); i++) {
						sb.append(",").append(nt_photopath.get(i).getFile_id());
					}
				}else if (nt_photopath.size()==1) {
					sb.append(nt_photopath.get(0).getFile_id());
				}
				bodyParams.put("file_ids", sb.toString());
			}
			bodyParams.put("message", message);
			if (selToolData.getCheckBoxIsCheck()) {
				bodyParams.put("is_anonymous", "1");
			}else {
				bodyParams.put("is_anonymous", "0");
			}
			HttpBaseRequest request  =  Wxxr.getInstance().postBaseRequest(pageurl, bodyParams,null);
			 TaskManager.startHttpRequest(request, new postNewTopicTag(request),  TopicAndPostResultBean.class);	
		}else {
			Toast.makeText(mContext, "请填写话题内容", 1).show();
		}
		
		 
		 
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == -1) {
			String path = null;
			try {
				path = selToolData.setPicture(requestCode, resultCode, data);
//				Uri mImageCaptureUri = data.getData(); 
//				if (mImageCaptureUri != null) {  
//					path=  setImage(mImageCaptureUri);// 根据Uri处理并显示图片  
//                } 
				// 第一次是拍照或者选择照片 回来，第二次才是 裁剪完成
				Log.e("alan", "------------------path:"+path);
				ImageBean bean = new ImageBean();
				bean.setPath(path);
				photopath.add(bean);
				selToolData.setPhotoList(photopath);
				setImage();
				if (requestCode == CameraHelp.SURVEY_PHOTO_ZOOM) {
				//裁剪完成的.
				}
			} catch (Throwable ee) {
				QLog.debug(TAG, "内存不足===!!!!!!1");
				Toast.makeText(this, "内存不足", Toast.LENGTH_SHORT).show();
				path = null;
			}
			if (path != null) {
			}
		}
	}
	public void setImage() {
		int size = photopath.size();
		if (size == 0) {
			seltool_imgs.setVisibility(View.GONE);
			seltool_imgs_div_1.setVisibility(View.GONE);
			seltool_imgs_div_2.setVisibility(View.GONE);
			seltool_imgs_div_3.setVisibility(View.GONE);
			seltool_imgs_div_4.setVisibility(View.GONE);
		} else if (size == 1) {
			seltool_imgs.setVisibility(View.VISIBLE);
			seltool_imgs_div_1.setVisibility(View.VISIBLE);
			seltool_imgs_div_2.setVisibility(View.GONE);
			seltool_imgs_div_3.setVisibility(View.GONE);
			seltool_imgs_div_4.setVisibility(View.GONE);
			String showUrl = "file://"+photopath.get(0).getPath();  
			ImageLoader.getInstance().displayImage(showUrl, photo1,options);
		} else if (size == 2) {
			seltool_imgs.setVisibility(View.VISIBLE);
			seltool_imgs_div_1.setVisibility(View.VISIBLE);
			seltool_imgs_div_2.setVisibility(View.VISIBLE);
			seltool_imgs_div_3.setVisibility(View.GONE);
			seltool_imgs_div_4.setVisibility(View.GONE);
			String showUrl_0 = "file://"+photopath.get(0).getPath();
			ImageLoader.getInstance().displayImage(showUrl_0, photo1,options);
			String showUrl_1 = "file://"+photopath.get(1).getPath();
			ImageLoader.getInstance().displayImage(showUrl_1, photo2,options);
			String mString= "22";
			int id =Integer.parseInt(mString);

		} else if (size == 3) {
			seltool_imgs.setVisibility(View.VISIBLE);
			seltool_imgs_div_1.setVisibility(View.VISIBLE);
			seltool_imgs_div_2.setVisibility(View.VISIBLE);
			seltool_imgs_div_3.setVisibility(View.VISIBLE);
			seltool_imgs_div_4.setVisibility(View.GONE);
			String showUrl_1 = "file://"+photopath.get(0).getPath();
			ImageLoader.getInstance().displayImage(showUrl_1, photo1,options);
			
			String showUrl_2 = "file://"+photopath.get(1).getPath();
			ImageLoader.getInstance().displayImage(showUrl_2, photo2,options);
			
			String showUrl_3 = "file://"+photopath.get(2).getPath();
			ImageLoader.getInstance().displayImage(showUrl_3, photo3,options);
		}else if(size == 4){
			seltool_imgs.setVisibility(View.VISIBLE);
			seltool_imgs_div_1.setVisibility(View.VISIBLE);
			seltool_imgs_div_2.setVisibility(View.VISIBLE);
			seltool_imgs_div_3.setVisibility(View.VISIBLE);
			seltool_imgs_div_4.setVisibility(View.VISIBLE);
			String showUrl_1 = "file://"+photopath.get(0).getPath();
			ImageLoader.getInstance().displayImage(showUrl_1, photo1,options);
			
			String showUrl_2 = "file://"+photopath.get(1).getPath();
			ImageLoader.getInstance().displayImage(showUrl_2, photo2,options);
			
			String showUrl_3 = "file://"+photopath.get(2).getPath();
			ImageLoader.getInstance().displayImage(showUrl_3, photo3,options);
			
			String showUrl_4 = "file://"+photopath.get(3).getPath();
			ImageLoader.getInstance().displayImage(showUrl_4, photo4,options);
		}
	}
	class postNewTopicTag implements ITag {
		HttpBaseRequest request ;
		public postNewTopicTag(HttpBaseRequest request){
			this.request = request ;
		}
		@Override
		public void refreshUI(Object t, DataState ds) {
			// TODO Auto-generated method stub
			finishProgress();
			if (t instanceof TopicAndPostResultBean) {
				TopicAndPostResultBean bean = (TopicAndPostResultBean)t;
				if (bean.getError()==null) {
					Toast.makeText(mContext, "成功", 1).show();
					MobclickAgent.onEvent(mContext, "topic_counts");
					NewTopicActivity.this.setResult(RESULT_OK);
					NewTopicActivity.this.finish();
					if (bean.getStats().getDay()==1) {
						MobclickAgent.onEvent(mContext, "day_topic_counts");
					}else if (bean.getStats().getWeek()==1) {
						MobclickAgent.onEvent(mContext, "week_topic_counts");
					}else if (bean.getStats().getMonth()==1){
						MobclickAgent.onEvent(mContext, "month_topic_counts");
					}
				}else {
					Toast.makeText(mContext, "失败"+bean.getDesc(), 1).show();
				}
			}
		}
		@Override
		public boolean refreshError(DataParseError parseError) {
			// TODO Auto-generated method stub
			finishProgress();
			Toast.makeText(mContext, "失败", 1).show();
			return false;
		}
		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub
			
		}
		}
	public void putphoto(File file) {
		showProgress("正在发送请稍等...");
		String  pageurl = KidConfig.UPLOAD_PHOTO;
		HttpBaseRequest request  =  Wxxr.getInstance().uploadFile(pageurl,file);
		 TaskManager.startHttpRequest(request, new putphotoTag(),  FileMetas.class);
	}
	class putphotoTag implements ITag {

		@Override
		public void refreshUI(Object t, DataState ds) {
			// TODO Auto-generated method stub
			if (t instanceof FileMetas) {
				FileMetas bean = (FileMetas)t;
				Log.e("alan", "---------------getDownload_url---path:"+bean.getDownload_urls().getOrigin().getUrl());
				ImageBean ibean = new ImageBean();
				ibean.setFile_id(bean.getFile_id());
				photopath.remove(0);
				nt_photopath.add(ibean);
				if (photopath.size()>0) {
					File file = new File(photopath.get(0).getPath());
					putphoto(file);
				}else {
					getTopiclist();
				}
				
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			// TODO Auto-generated method stub
			finishProgress();
			Toast.makeText(mContext, "图片上传失败", 1).show();
			return false;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub
		}
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.close1:
			seltool_imgs_div_1.setVisibility(View.GONE);
			photopath.remove(0);
			setImage();
			break;
		case R.id.close2:
			seltool_imgs_div_3.setVisibility(View.GONE);
			photopath.remove(1);
			setImage();
			break;
		case R.id.close3:
			seltool_imgs_div_3.setVisibility(View.GONE);
			photopath.remove(2);
			setImage();
			break;
		case R.id.close4:
			seltool_imgs_div_4.setVisibility(View.GONE);
			photopath.remove(3);
			setImage();
			break;

		default:
			break;
		}
	}
	public void inintdialog() {
		dialog.showDialog(this, "温馨提示", "丢弃所有内容并退出?", true, new DialogCallBack() {
			
			@Override
			public void onClick(int what) {
				doClick(what);
			}
		});
	}
	protected void doClick(int what) {
		switch (what) {
		case IDialog.YES:
			NewTopicActivity.this.finish();
			break;
		case IDialog.CANCLE:
			dialog.dismissProgress(null);
			break;
		default:
			break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if(KeyEvent.KEYCODE_BACK == keyCode){
			if (send_topic_text.getText().toString().length()>0||photopath.size()>0) {
				inintdialog();
			}else {
				finish();
			}
		}
		return super.onKeyDown(keyCode, event);
	}
	public Bitmap  decodeBitmap(String pathName) {
		File file = new File(pathName);
		Bitmap cameraBitmap =BitmapFactory.decodeFile(pathName);
		int degree = readPictureDegree(file.getAbsolutePath()); 
		return rotaingImageView(degree, cameraBitmap);
	}
	/**
	 * 读取图片属性：旋转的角度
	 * @param path 图片绝对路径
	 * @return degree旋转的角度
	 */
    public static int readPictureDegree(String path) {
    	int degree = 0;  
        ExifInterface exif = null;  
        try {  
            exif = new ExifInterface(path);  
        } catch (IOException ex) {  
        }  
        if (exif != null) {  
        int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, -1);  
            if (orientation != -1) {  
                switch(orientation) {  
                    case ExifInterface.ORIENTATION_ROTATE_90:  
                        degree = 90;  
                        break;  
                    case ExifInterface.ORIENTATION_ROTATE_180:  
                        degree = 180;  
                        break;  
                    case ExifInterface.ORIENTATION_ROTATE_270:  
                        degree = 270;  
                        break;  
                }  
            }  
        }  
        return degree;  
    }
    public static Bitmap rotaingImageView(int angle , Bitmap bitmap) {  
        //旋转图片 动作  
        Matrix matrix = new Matrix();;  
        matrix.postRotate(angle);  
        System.out.println("angle2=" + angle);  
        // 创建新的图片  
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,  
                bitmap.getWidth(), bitmap.getHeight(), matrix, true);  
        return resizedBitmap;  
    }
	private String setImage(Uri mImageCaptureUri) {

		// 不管是拍照还是选择图片每张图片都有在数据中存储也存储有对应旋转角度orientation值
		// 所以我们在取出图片是把角度值取出以便能正确的显示图片,没有旋转时的效果观看
		String filePath ="";
		ContentResolver cr = this.getContentResolver();
		Cursor cursor = cr.query(mImageCaptureUri, null, null, null, null);// 根据Uri从数据库中找
		if (cursor != null) {
			cursor.moveToFirst();// 把游标移动到首位，因为这里的Uri是包含ID的所以是唯一的不需要循环找指向第一个就是了
			filePath = cursor.getString(cursor.getColumnIndex("_data"));// 获取图片路
			String orientation = cursor.getString(cursor
					.getColumnIndex("orientation"));// 获取旋转的角度
			cursor.close();
		}
		return filePath;
	}
	public String nativeCompressBitmap(final String path) {
		new Thread(new Runnable() {
			public void run() {
				try {
					int quality = 90;//original
					quality=50;//同学们可以与原生的压缩方法对比一下，同样设置成50效果如何 
					String filename=path;
					BitmapFactory.Options opts = new BitmapFactory.Options();
					opts.inSampleSize = 1;
					Bitmap bit = BitmapFactory.decodeFile(filename, opts);
					String dirFile = Environment.getExternalStorageDirectory().toString()+"/hsh/bmpcache/";
					File originalFile = new File(dirFile,"bitcompress.jpg");
					FileOutputStream fileOutputStream = new FileOutputStream(
							originalFile);
					bit.compress(CompressFormat.JPEG, quality, fileOutputStream);
					File jpegTrueFile = new File(dirFile,System.currentTimeMillis()+".jpg");
					NativeUtil.compressBitmap(bit, quality,
							jpegTrueFile.getAbsolutePath(), true);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}).start();
		return path;
	}
	
}
